<!--**
* @author: SEKin
* @Date: 2024-11-04
* @description:  数据源
* @Last Modified time:
*-->
<template>
  <div class="view-container">
    <PageLayout
      :api-methods="api"
      :head-config="headConfig"
      :common-config="commonConfig"
      :modal-config="modalConfig"
      :tab-config="tabConfig"
      ref="pageLayoutRef"
    >
      <template #modalInfo="modalData">
        <ModalInfo
          :show="modalData.show"
          v-model:info="modalData.info"
          :tagList="stateData"
          :cur-node="modalData.curNode"
        />
      </template>
      <template #tableRow="{ column, record }">
        <template v-if="column.dataIndex == 'useCache'">
          <span
            :style="{
              color:
                record.useCache == 0
                  ? 'var(--textColorSide)'
                  : 'var(--themeColor)',
            }"
            >{{ record.useCache == '0' ? '禁用' : '启用' }}</span
          >
        </template>
        <template v-if="column.dataIndex == 'elType'">
          <span>{{ tagObjByName.elType[record.elType] }}</span>
        </template>
        <template v-if="column.dataIndex == 'businessType'">
          <span>{{ tagObjByName.elBusinessType[record.businessType] }}</span>
        </template>
      </template>
      <template #headOptBtns>
        <Button
          type="primary"
          :data-warden-title="generateWardenTit('初始化规则库')"
          v-if="initAuth"
          @click="eventHandle.init"
          >初始化规则库</Button
        >
      </template>
      <template #headCondition="{ headCondition, updateConditon }">
        <Select
          :options="stateData.elBusinessTypeArr"
          show-search
          allow-clear
          :bordered="true"
          :field-names="{ label: 'name', value: 'code' }"
          option-filter-prop="name"
          :value="headCondition.businessType"
          @change="(v) => updateConditon('businessType', v as string)"
          placeholder="业务类型...."
          style="width: 220px"
        />
      </template>
    </PageLayout>
  </div>
</template>
<script setup lang="ts" name="system-rule">
import PageLayout from 'components/src/pageLayout/PageLayout.vue';
import Api, { IRuleInfoNode, IRuleNode } from 'apis/src/users/rule';
import type {
  IApiMethods,
  ICommonConfig,
  IModalInfoConfig,
  ITabConfig,
  IPageLayOutExpose,
  IHeadConfig,
} from 'components/src/pageLayout/page';
import ModalInfo from './ModalInfo.vue';
import { generateWardenTit } from 'components/src/pageLayout/util';
import { message, Button, Select } from 'ant-design-vue';
import { useAuthCode } from 'components/src/pageLayout/useAuthCode';
import { computed, reactive, ref } from 'vue';
import PApi, { IParameter } from 'apis/src/users/common';
import { AnyObj } from 'commons/src/common';

const pageLayoutRef = ref<IPageLayOutExpose<IRuleNode>>();
const codeModuleStr = 'rule';
// 公共配置
const commonConfig: ICommonConfig<IRuleNode, 'init'> = {
  name: {
    theme: '规则库', // 该模块页面的名称
  },
  fieldData: {
    idField: 'id',
    nameField: 'name',
  },
  codeLimits: {
    add: [`users:${codeModuleStr}:add`, '新增规则库'],
    del: [`users:${codeModuleStr}:del`, '删除'],
    edit: [`users:${codeModuleStr}:edit`, '修改'],
    batchDel: [`users:${codeModuleStr}:del`, '批量删除'],
    init: [`users:${codeModuleStr}:init`, '初始化规则库'],
  }, // 页面的权限按钮编码
};

// const editAuth = useAuthCode(commonConfig.codeLimits.edit[0]);
const initAuth = useAuthCode(commonConfig.codeLimits.init[0]);

// api 请求配置
const api: IApiMethods<IRuleNode, IRuleInfoNode, HeadCondtion> = {
  list: Api.page,
  del: Api.dels,
  add: Api.add,
  edit: Api.update,
};

// 头部配置

type HeadCondtion = {
  businessType: string | undefined;
};
const headConfig: IHeadConfig<HeadCondtion> = {
  headBtnIsAdd: true,
  apiSearchField: 'key',
  tip: '搜索名称或el前缀...',
  initState() {
    return {
      businessType: undefined,
    };
  },
};

// 模态框配置
const modalConfig: IModalInfoConfig<IRuleNode, IRuleInfoNode> = {
  initInfo() {
    return {
      elPrefix: '',
      businessType: '',
      elType: '',
      methodName: '',
      description: '',
      name: '',
      dataSource: '',
      useCache: 0,
      cacheTtl: 10,
      elParams: [],
      paramParams: [],
      freemarkerTemplate: '',
    };
  },
  className: 'ruleModal',
  width: 1000,
};

// 表格配置

const tabConfig: ITabConfig<IRuleNode> = {
  cols: [
    {
      title: '名称',
      dataIndex: 'name',
      width: '16%',
    },
    {
      title: '选定的数据源',
      dataIndex: 'dataSource',
      width: 104,
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
    },
    {
      title: 'el类型',
      dataIndex: 'elType',
      width: 130,
    },
    {
      title: 'el前缀',
      dataIndex: 'elPrefix',
    },

    {
      title: '路由名称',
      dataIndex: 'methodName',
    },
    {
      title: '是否缓存',
      dataIndex: 'useCache',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: '14%',
    },
  ],
  noTree: true,
};

/**
 *@description 状态保存区
 */
type State = {
  elTypeArr: IParameter[];
  elBusinessTypeArr: IParameter[];
  ruleRouteArr: IParameter[];
};
const stateData = reactive<State>({
  elBusinessTypeArr: [],
  elTypeArr: [],
  ruleRouteArr: [],
});

PApi.getListByTagList(['elBusinessType', 'elType', 'ruleRoute']).then((res) => {
  const { elBusinessType, elType, ruleRoute } = res.data;
  stateData.elBusinessTypeArr = elBusinessType;
  stateData.ruleRouteArr = ruleRoute.map((val: IParameter) => {
    val.name = `${val.name} — ${val.code}`;
    return val;
  });
  stateData.elTypeArr = elType;
});

const tagObjByName = computed(() => {
  const fn = (arr: IParameter[]) => {
    const obj: AnyObj = {};
    arr.forEach((i) => {
      obj[i.code] = i.name;
    });

    return obj;
  };
  return {
    elBusinessType: fn(stateData.elBusinessTypeArr),
    elType: fn(stateData.elTypeArr),
  };
});

const eventHandle = {
  init() {
    Api.initRule().then(() => {
      message.success('初始化成功！');
      pageLayoutRef.value?.refreshTab();
    });
  },
};
</script>
<style lang="scss">
.ruleModal.commonModal {
  padding: 0;
  padding-right: 6px;
}
</style>
